import { createConnection, Connection, ConnectionOptions ,getConnectionOptions, ObjectType, Repository} from "typeorm";
let  mysql =require("../../config/mysql")
let connection: Connection | null = null;
let repositorys:any=[];
 

const getConnection = async () => {
    if (connection) {
        return Promise.resolve(connection);
      }
 
      
    connection = await createConnection({
      type: 'mysql',
      ...mysql.development,
      entities: [
          __dirname + '/../../**/*.entity{.ts,.js}',
      ],
      synchronize:true,
      // logging: true,
    });
    return connection;
}

async function getRepository<Entity>(entityClass: ObjectType<Entity>): Promise<Repository<Entity>> {
    let rep=repositorys[entityClass.name];
    if(!rep){
      const connection: Connection = await getConnection();
      rep=connection.getRepository(entityClass);
      repositorys[entityClass.name]=rep;
    }
    
    return rep;
    
  }

export default {getConnection,getRepository};

 